package com.hzg.lanya.frame;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.hzg.lanya.R;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 大数据传输，即突破一次只能发送20字节的限制，须手机系统不低于Android5.0
 * Created by Administrator on 2017/8/10 0010.
 */

public class MtuFragment extends Fragment {
    private static final String TAG = "MtuFragment";


    private Spinner mSpinnerDevice;
    private EditText mEdtTxData;
    private EditText mEdtMtu;
    private CheckBox mBoxEncrypt;
    private TextView mTxtRxData;
    private String mSelectedAddress;
    private int mDataType = -1;
    private ArrayAdapter<String> mDeviceAdapter;

    private int mMtu = 23;
    private TextView nametable;
    private String address;
    private EditText edttime;
    private MyAdapter mMyAdapter;
    private EditText edt_cz1;
    private EditText edt_cz2;
    private EditText edt_cz3;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        zcMyGb();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_mtu, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
// 获取布局中新增的视图
        ImageView profileImage = view.findViewById(R.id.profile_image);
        TextView personName = view.findViewById(R.id.person_name);
        TextView dateTime = view.findViewById(R.id.date_time);
        TextView highPressure = view.findViewById(R.id.high_pressure_value);
        TextView lowPressure = view.findViewById(R.id.low_pressure_value);
        TextView heartRate = view.findViewById(R.id.heart_rate_value);

        // 设置默认数据
        personName.setText("Mom");
        dateTime.setText("2015-07-08 10:22");
        highPressure.setText("121");
        lowPressure.setText("84");
        heartRate.setText("72");

//        mEdtTxData = (EditText) view.findViewById(R.id.edt_tx_data);
//        mEdtMtu = (EditText) view.findViewById(R.id.edt_mtu);
//        view.findViewById(R.id.btn_send).setOnClickListener(this);
//        view.findViewById(R.id.btn_update_mtu).setOnClickListener(this);

//        edt_cz1=(EditText)view.findViewById(R.id.edtcz1);
//        edt_cz2=(EditText)view.findViewById(R.id.edtcz2);
//        edt_cz3=(EditText)view.findViewById(R.id.edtcz3);
//
//        nametable=(TextView) view.findViewById(R.id.nametable);
//
//
//
//
//        edttime=(EditText)view.findViewById(R.id.edttime);
//        Button btnstart=(Button)view.findViewById(R.id.btnstart);
//        Button btnstop=(Button)view.findViewById(R.id.btnstop);
//        Button btn_excel=(Button)view.findViewById(R.id.btn_excel);
//        btn_excel.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                excelExecute(deviceList);//导出电子表格
//            }
//        });
//        Button btn_close=(Button)view.findViewById(R.id.btn_close);
//        btn_close.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                //清空数据
//                deviceList.clear();
//                utils.setSharedPreferences(getActivity(),"JL_XML",deviceList);
//                mMyAdapter.notifyDataSetChanged();
//            }
//        });
//        btnstart.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (!START){
//
//                    setTextTable("等待应答");
//                    send(start());
//
////                    //测试
////                    START=true;
////                    setTimer();//启动后开始计时
//                }
//
//            }
//        });
//        btnstop.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (START){
//                    setTextTable("等待应答");
//                    send(stop());
//
////                    //测试
////                    START=false;
////                    closeTime();//停止计时
////                    addData();//添加记录
//                }
//            }
//        });



//        ListView listview=(ListView)view.findViewById(R.id.listview);
//        deviceList=utils.getSharedPreferences(getActivity(),"JL_XML");
//        mMyAdapter=new MyAdapter();
//        listview.setAdapter(mMyAdapter);

    }

    /**
     * 添加记录
     */
    private void addData(){
        String dl=""+edt_cz1.getText();
        String dy=""+edt_cz2.getText();
        String dz=""+edt_cz3.getText();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate =  new Date(System.currentTimeMillis());
        String rq  =  formatter.format(curDate);
        rq=rq.replace("20","");
        DateFormat df = new SimpleDateFormat("HH:mm");
        String sj=df.format(new Date());
        HashMap<String, Object> m =new HashMap<String, Object>();
        m.put("bh",""+(deviceList.size()+1));
        m.put("rq",rq);
        m.put("sj",sj);
        m.put("dl",dl);
        m.put("dy",dy);
        m.put("dz",dz);
        deviceList.add(m);
        utils.setSharedPreferences(getActivity(),"JL_XML",deviceList);
        mMyAdapter.notifyDataSetChanged();
    }

    boolean START=false;
    Timer mTimer;
    Handler handler=new Handler();
    long countTime=0;
    private void setTimer(){
        countTime=0;
        if (mTimer!=null)return;
        mTimer=new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        countTime++;
                        edttime.setText(""+countTime);
                    }
                });
            }
        },1,1000);
    }

    private void closeTime(){
        if (mTimer!=null)
            mTimer.cancel();
        mTimer=null;
    }



    /**
     * 接收到传回来的数据
     * @param dataStr
     */
    public void displayRxData(String dataStr) {

            //dataStr += "收到数据: " + DataUtil.byteArrayToHex(data) + '\n';

           Toast.makeText(getActivity(),"收到数据："+dataStr, Toast.LENGTH_SHORT).show();

            if (dataStr!=null && dataStr.length()>=16){
                String host=dataStr.substring(0,4);
                String A5=dataStr.substring(0,2);
                if (host.equals("A0A2")){
                    setTextTable("启动成功");
                    START=true;
                    setTimer();//启动后开始计时
                }else if (host.equals("A0A3")){
                    setTextTable("停止成功");
                    START=false;
                    closeTime();//停止计时
                    addData();//添加记录
                }else if (A5.equals("A5")){
                    //数据传上来
                    chaoZuoJXZL(dataStr);//解析数据设置值
                    addData();//添加记录
                    send("A0A5000000000000");//应答收到
                }else {
                    setTextTable("失败，未知指令:"+dataStr);
                }
            }else {
                setTextTable("失败:"+dataStr);
            }
    }





    // 向设备发送数据
    private void send(String inputStr) {

       // Toast.makeText(getActivity(),"发送："+inputStr, Toast.LENGTH_SHORT).show();
        MyConfig.mScanFragment.send(inputStr);

    }


    private String name="未连接";
    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume()");
        Log.i("Flog", "---");
        name = MyConfig.name;
        address = MyConfig.address;
       // setTextTable("");
        Log.i("Flog", "---"+name+"-"+address);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("Flog","销毁记录页面");
        getActivity().unregisterReceiver(bootCompleteReceiver);//自己定义收消息的广播
        if (mTimer!=null)
            mTimer.cancel();
    }

    private void setTextTable(String str){
        nametable.setText(name+"      "+str);
    }



    /**
     * 合成启动指令
     * @return
     */
    private String start(){
        String str="A2A2000000000000";
        return str;
    }
    /**
     * 合成停止指令
     * @return
     */
    private String stop(){
        String str="A3A3000000000000";
        return str;
    }

    /**
     * 操作解析指令并设置各类值
     * @param zl
     */
    private void chaoZuoJXZL(String zl){

        String dl=zl.substring(2,8);
        String dy=zl.substring(8,14);
        String dz=zl.substring(14,20);
        String dl_z=zl.substring(2,6);
        String dl_x=zl.substring(6,8);
        String dy_z=zl.substring(8,12);
        String dy_x=zl.substring(12,14);
        String dz_z=zl.substring(14,18);
        String dz_x=zl.substring(18,20);
        edt_cz1.setText(utils.hexToInt(dl_z)+"."+utils.hexToInt(dl_x));
        edt_cz2.setText(utils.hexToInt(dy_z)+"."+utils.hexToInt(dy_x));
        edt_cz3.setText(utils.hexToInt(dz_z)+"."+utils.hexToInt(dz_x));
    }


    ArrayList<HashMap<String, Object>> deviceList;
    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return deviceList.size();
        }

        @Override
        public Object getItem(int position) {
            return deviceList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = getLayoutInflater().inflate(R.layout.layout_text,null);

            TextView n1=(TextView)convertView.findViewById(R.id.txt_name1);
            TextView n2=(TextView)convertView.findViewById(R.id.txt_name2);
            TextView n3=(TextView)convertView.findViewById(R.id.txt_name3);
            TextView n4=(TextView)convertView.findViewById(R.id.txt_name4);
            TextView n5=(TextView)convertView.findViewById(R.id.txt_name5);
            TextView n6=(TextView)convertView.findViewById(R.id.txt_name6);

            HashMap<String, Object> map=(HashMap<String, Object>)deviceList.get(deviceList.size()-position-1);
            n1.setText(""+map.get("bh"));
            n2.setText(""+map.get("rq"));
            n3.setText(""+map.get("sj"));
            n4.setText(""+map.get("dl"));
            n5.setText(""+map.get("dy"));
            n6.setText(""+map.get("dz"));




//            Boolean zt = devicemsg.getIsOnline();
//            if (zt){
//                holder.sbzt.setText("在线");
//                holder.sbzt.setTextColor(0xff000000);
//            }else {
//                holder.sbzt.setText("离线");
//                holder.sbzt.setTextColor(0xffebebeb);
//            }


            return convertView;
        }


    }




    private void excelExecute(ArrayList<HashMap<String, Object>> list) {
        String dirPath = Environment.getExternalStorageDirectory() + File.separator + "AndroidExcel";
        File file = new File(dirPath);
        if (!file.exists())
            file.mkdirs();
        String testExcelPath = dirPath + File.separator + "testExcel.xls";
        String[] colName = {"编号", "日期", "时间", "电流",
                "电压", "电阻"};
        ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("表格创建中...");
        progressDialog.show();
        ExcelUtil.initExcel(testExcelPath, "测试表1", colName);
//        ExcelUtil.setSheetHeader(this, testExcelPath, colName, "测试表1", list);

        ExcelUtil.writeObjListToExcel(list, testExcelPath, getActivity());
        progressDialog.dismiss();
    }




    /**
     * 自己定义收消息的广播
     */
    public BootCompleteReceiver bootCompleteReceiver=new BootCompleteReceiver();
    private void zcMyGb(){
        IntentFilter intentFilter=new IntentFilter(MyConfig.MY_MSG_GB);
        getActivity().registerReceiver(bootCompleteReceiver,intentFilter);
    }

    public class BootCompleteReceiver extends BroadcastReceiver {
        public BootCompleteReceiver(){

        }

        @Override
        public void onReceive(Context context, Intent intent) {//下面的语句根据自己的需求来写
            String a=intent.getAction();
            if (a.equals(MyConfig.MY_MSG_GB)){
                String name=intent.getStringExtra("key");
                if (MyConfig.SEND_MSG.equals(name) || name.length()<5)return;
                name=name.replace(" ","");
                //Toast.makeText(context, "收到数据："+name, Toast.LENGTH_SHORT).show();
                Log.i("Flog22","ment收到消息："+name);
                displayRxData(name);
            }

        }
    }


}